package com.carkeeper.shop.check.service.impl;
import com.aliyuncs.exceptions.ClientException;
import com.carkeeper.entity.Result;
import com.carkeeper.entity.StatusCode;
import com.carkeeper.shop.check.dao.StoreUserMapper;
import com.carkeeper.shop.check.service.StoreUserService;
import com.carkeeper.shop.check.dao.StoreMapper;
import com.carkeeper.shop.pojo.Store;
import com.carkeeper.shop.pojo.StoreUser;
import com.carkeeper.utile.BcryptUtil;
import com.carkeeper.utile.SMSUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class StoreUserServiceImpl implements StoreUserService {

    @Autowired
    private StoreUserMapper storeUserMapper;

    @Autowired
    private StoreMapper storeMapper;

    /**
     * 已通过审核的服务商的展示
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Store> findPage(Map searchMap, String page, String size) {
        int pageNum;
        int pageSize;
        if (page == null) {
            pageNum = 1;
        }
        pageNum = Integer.parseInt(page);
        if (size == null) {
            pageSize = 15;
        }
        pageSize = Integer.parseInt(size);
        PageHelper.startPage(pageNum, pageSize);

        //1.查询商家信息
        Example example = new Example(Store.class);
        Example.Criteria criteria = example.createCriteria();

        //主体编码
        if (searchMap.get("code") != null && !"".equals(searchMap.get("code"))) {
            criteria.andEqualTo("code", searchMap.get("code"));
        }
        //主体简称
        if (searchMap.get("simpleName") != null && !"".equals(searchMap.get("simpleName"))) {
            criteria.andLike("simpleName", "%" + (String) searchMap.get("simpleName") + "%");
        }
        //主体类型
        if (searchMap.get("type") != null && !"".equals(searchMap.get("type"))) {
            criteria.andEqualTo("type", searchMap.get("type"));
        }
        if (searchMap.get("isChain") != null && !"".equals(searchMap.get("isChain"))) {
            criteria.andEqualTo("isChain", searchMap.get("isChain"));
        }
        //状态
        if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
            criteria.andEqualTo("status", searchMap.get("status"));
        }
        //主体所属区域
        if (searchMap.get("province") != null && !"".equals(searchMap.get("province"))) {
            criteria.andEqualTo("province", searchMap.get("province"));
        }
        if (searchMap.get("city") != null && !"".equals(searchMap.get("city"))) {
            criteria.andEqualTo("city", searchMap.get("city"));
        }
        if (searchMap.get("county") != null && !"".equals(searchMap.get("county"))) {
            criteria.andEqualTo("county", searchMap.get("county"));
        }

        //审核已通过服务商信息
        criteria.andEqualTo("check", "1");
        List<Store> storeList = storeMapper.selectByExample(example);
        //2.查询商家用户表信息
        StoreUser storeUser;
        for (Store store : storeList) {
            String id = store.getId();
            storeUser = storeUserMapper.selectByPrimaryKey(id);
            store.setStoreUser(storeUser);
        }
        return (Page<Store>) storeList;
    }

    /**
     * 创建管理员
     *
     * @param id
     * @return
     */
    @Override
    public Map createAdmin(String id) {
        if (id == null || "".equals(id)) {
            return null;
        }
        Store store = storeMapper.selectByPrimaryKey(id);
        Map<String, String> map = new HashMap<>();
        map.put("storeId", store.getId());
        map.put("contactName", store.getContactName());
        map.put("contactPhone", store.getContactPhone());
        return map;
    }

    /**
     * 创建管理员
     *
     * @param storeUser
     */
    @Override
    public Result saveAdmin(StoreUser storeUser) {
        //0.判断当前的数据是否为null
        if (storeUser == null) {
            return new Result(true, StatusCode.OK, "数据为空");
        }
        //1.查询数据库判断:当前的手机号是否重复 ,当前要创建的用户名是否重复,当前店铺是否已创建过管理员
        List<StoreUser> mapper = storeUserMapper.findByStoreId(storeUser.getPhone(), storeUser.getUsername(), storeUser.getStoreId());
        if (mapper != null && mapper.size() > 0) {
            return new Result(true, StatusCode.OK, "创建管理员失败");
        }
        Store store = storeMapper.selectByPrimaryKey(storeUser.getStoreId());
        //发送阿里云短息
        try {
            SMSUtils.sendShortMessage("SMS_205810866", storeUser.getPhone(), storeUser.getUsername(), storeUser.getPassword());
        } catch (ClientException e) {
            e.printStackTrace();
            System.out.println("阿里云短信发送失败");
        }
        //2.调用Bcrypt方式对密码进行加密
        String encrypt = BcryptUtil.encrypt(storeUser.getPassword());
        storeUser.setPassword(encrypt);
        storeUser.setIsAdmin("1");//设置为管理员
        if (store.getType() != null) {
            storeUser.setType(Integer.parseInt(store.getType())); //标明是什么商家
        }
        storeUser.setStatus("0");//默认未锁定的状态
        //3.把数据存入数据库，返回结果
        storeUserMapper.insertSelective(storeUser);
        return new Result(true, StatusCode.OK, "创建管理员成功");
    }

    /**
     * 查看用户
     *
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<StoreUser> userId(Map searchMap, String page, String size) {
        int pageNum;
        int pageSize;
        if (page == null) {
            pageNum = 1;
        }
        pageNum = Integer.parseInt(page);
        if (size == null) {
            pageSize = 15;
        }
        pageSize = Integer.parseInt(size);
        PageHelper.startPage(pageNum, pageSize);

        Example example = new Example(StoreUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap.get("username") != null && !"".equals(searchMap.get("username"))) {
            criteria.andEqualTo("username", searchMap.get("username"));
        }
        if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
            criteria.andEqualTo("name", searchMap.get("name"));
        }
        if (searchMap.get("phone") != null && !"".equals(searchMap.get("phone"))) {
            criteria.andEqualTo("phone", searchMap.get("phone"));
        }
        criteria.andEqualTo("storeId", searchMap.get("id"));
        List<StoreUser> storeUsers = storeUserMapper.selectByExample(example);
        return (Page<StoreUser>) storeUsers;
    }

    /**
     * 重置密码
     *
     * @param username
     */
    @Override
    public Result reset(String username) {
        if (username != null && !"".equals(username)) {
            //1.根据用户名查询数据库判断当前的用户是否存在，是否是一个锁定状态
            StoreUser storeUser = new StoreUser();
            storeUser.setUsername(username);
            StoreUser storeUser1 = storeUserMapper.selectOne(storeUser);
            Map map = new HashMap();
            map.put("storeId", storeUser1.getStoreId());
            if (storeUser1 != null) {
                //2.使用Bcrypt把密码重置为123456
                String encrypt = BcryptUtil.encrypt("123456");
                storeUser1.setPassword(encrypt);
                storeUserMapper.updateByPrimaryKeySelective(storeUser1);
                //3.调用阿里云短信，重置密码
                try {
                    SMSUtils.sendShortMessage("SMS_205825142", storeUser1.getPhone(), null, "123456");
                } catch (ClientException e) {
                    e.printStackTrace();
                }
                return new Result(true, StatusCode.OK, "重置密码成功", map);
            }
        }
        return new Result(false, StatusCode.ERROR, "重置密码失败");
    }

    /**
     * 锁定与解锁用户
     *
     * @param username
     * @return
     */
    @Override
    public Result lockUser(String username) {
        if (username == null) {
            return new Result(false, StatusCode.ERROR, "无法操作");
        }
        StoreUser storeUser = new StoreUser();
        storeUser.setUsername(username);
        StoreUser selectOne = storeUserMapper.selectOne(storeUser);
        if (selectOne == null) {
            return new Result(false, StatusCode.ERROR, "没有此用户");
        }
        String status = selectOne.getStatus();
        //未锁定改为锁定状态
        if ("0".equals(status)) {
            selectOne.setStatus("1");
        }
        if ("1".equals(status)) {
            selectOne.setStatus("0");
        }
        storeUserMapper.updateByPrimaryKeySelective(selectOne);
        Map map = new HashMap();
        map.put("storeId", selectOne.getStoreId());
        return new Result(true, StatusCode.OK, "修改状态成功", map);
    }
}
